﻿#region Copyright
// Partial Copyright (c) LogoUI Software Solutions LTD
// Author: Vladislav Spivak
// This source file is the part of LogoFX Framework http://logofx.codeplex.com
// See accompanying licences and credits.
#endregion

using System.Collections;
using System.Reflection;
using System.Windows;
#if !WinRT
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Interactivity;
using LogoFX.Core;
using EventTrigger = System.Windows.Interactivity.EventTrigger;
#else
using LogoFX.Core;
using Windows.UI.Interactivity;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Markup;
using Windows.UI.Xaml.Media;
using EventTrigger = Windows.UI.Interactivity.EventTrigger;
#endif

namespace LogoFX.Infra.Interactivity
{
    //todo:clarify usecase of this
    public class BindNamedPropertyBehavior : Behavior<FrameworkElement>
    {
        public string TargetProperty { get; set; }
        public string SourceProperty { get; set; }

        protected override void OnAttached()
        {
            base.OnAttached();
            AssociatedObject.Loaded += new RoutedEventHandler(AssociatedObject_Loaded);
        }
        protected override void OnDetaching()
        {
            base.OnDetaching();
            AssociatedObject.Loaded -= new RoutedEventHandler(AssociatedObject_Loaded);
        }
        void AssociatedObject_Loaded(object sender, RoutedEventArgs e)
        {
            SetPropertyBinding();
        }

        private void SetPropertyBinding()
        {
            DependencyObject currentElement = AssociatedObject;
            PropertyInfo sourceProperty = null;
            PropertyInfo targetProperty = AssociatedObject.GetType().GetProperty(TargetProperty);
            object currentSource = null;

            while (currentElement != null && sourceProperty == null)
            {
                currentSource = currentElement.GetValue(FrameworkElement.DataContextProperty);

                if (currentSource != null)
                    sourceProperty = currentSource.GetType().GetProperty(SourceProperty);

                //is have readable property
                if (sourceProperty == null || !sourceProperty.CanRead)
                {
                    currentElement = VisualTreeHelper.GetParent(currentElement);
                    sourceProperty = null;
                }
            }

        }

    }
}
